<template>
  <div class="daemonset">
    <el-row>
      <!-- 头部1，放namespace选择框, 刷新按钮 -->
      <el-col :span="24">
        <el-card class="deploy-head-card" shadow="never" :body-style="{padding:'10px'}">
          <el-row>
            <!-- namespace下拉选择框 -->
            <el-col :span=8>
              <span style="font-size: 14px;">命名空间：</span>
              <el-select
                  @change="npChange"
                  size="small"
                  v-model="namespaceValue"
                  filterable>
                <el-option
                    v-for="(item, index) in namespaceList"
                    :key="index"
                    :label="item.metadata.name"
                    :value="item.metadata.name"></el-option>
              </el-select>
            </el-col>
            <el-col :span="16" style="text-align:right;">
              <el-button size="small" icon="Refresh" plain @click="getDaemonSets()">刷新</el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <!-- 头部2，创建按钮 及搜索框 -->
      <el-col :span="24">
        <el-card class="daemonset-head-card" shadow="never" :body-style="{padding:'10px'}">
          <!-- float属性，会将多个同级标签放在同一行 -->
          <div style="float: left;margin-right:10px;">
            <el-button   size="small" type="primary" icon="Edit" @click="createDaemonsetDrawer = true" >创建</el-button>
          </div>
          <div>
            <el-input class="daemonset-head-search" size="small" clearable placeholder="请输入" v-model='searchValue'></el-input>
            <el-button size="small" type="primary" plain icon="Edit" @click="getDaemonSets()">搜索</el-button>
          </div>
        </el-card>
      </el-col>
      <!-- 数据表格 -->
      <el-col :span="24">
        <div>
          <el-card class="daemonset-body-card" shadow="never" :body-style="{padding:'5px'}">
            <el-table
                style="width:100%;font-size:12px;margin-bottom:10px;"
                :data="daemonSetList"
                v-loading="appLoading">
              <el-table-column width="20"></el-table-column>
              <el-table-column align=left label="DaemonSet名">
                <template v-slot="scope">
                  <a class="daemonset-body-daemonsetname">{{ scope.row.metadata.name }}</a>
                </template>
              </el-table-column>
              <el-table-column align=center label="标签">
                <template v-slot="scope">
                  <div v-for="(val, key) in scope.row.metadata.labels" :key="key">
                    <el-popover
                        placement="right"
                        :width="200"
                        trigger="hover"
                        :content="key + ':' + val">
                      <template #reference>
                        <el-tag style="margin-bottom: 5px" type="warning">{{ ellipsis(key + ":" + val) }}</el-tag>
                      </template>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align=center label="容器组">
                <template v-slot="scope">
                  <span>{{ scope.row.status.numberAvailable>0?scope.row.status.numberAvailable:0  }} / {{ scope.row.status.desiredNumberScheduled>0?scope.row.status.desiredNumberScheduled:0 }} </span>
                </template>
              </el-table-column>
              <el-table-column align=center min-width="100" label="创建时间">
                <template v-slot="scope">
                  <el-tag type="info">{{ timeTrans(scope.row.metadata.creationTimestamp) }} </el-tag>
                </template>
              </el-table-column>
              <el-table-column align=center label="镜像">
                <template v-slot="scope">
                  <div v-for="(val, key) in scope.row.spec.template.spec.containers" :key="key">
                    <el-popover
                        placement="right"
                        :width="200"
                        trigger="hover"
                        :content="val.image">
                      <template #reference>
                        <el-tag style="margin-bottom: 5px">{{ ellipsis(val.image.split('/')[2]==undefined?val.image:val.image.split('/')[2]) }}</el-tag>
                      </template>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align=center label="操作" width="200">
                <template v-slot="scope">
                  <el-button size="small" style="border-radius:2px;" icon="Edit" type="primary" plain @click="getDaemonSetDetail(scope)">YAML</el-button>
                  <el-button size="small" style="border-radius:2px;" icon="Delete" type="danger" @click="handleConfirm(scope, '删除', delDaemonSet)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                class="daemonset-body-pagination"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pagesizeList"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="daemonSetTotal">
            </el-pagination>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <!-- 创建 -->
    <el-drawer
        v-model="createDaemonsetDrawer"
        direction="rtl"
        :before-close="handleClose"
        title="创建Daemonset">
      <template #default>
        <!-- flex布局,居中 -->
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <!-- ref绑定控件后，js中才能用this.$ref获取该控件 -->
            <!-- rules 定义form表单校验规则 -->
            <el-form ref="createDaemonset" :rules="createDaemonsetRules" :model="createDaemonset" label-width="80px">
              <!-- prop用于rules中的校验规则的key -->
              <el-form-item class="deploy-create-form" label="名称" prop="name">
                <el-input v-model="createDaemonset.name"></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="命名空间" prop="namespace">
                <el-select v-model="createDaemonset.namespace" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in namespaceList"
                      :key="index"
                      :label="item.metadata.name"
                      :value="item.metadata.name">
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- 数字输入框，最小为1，最大为10 -->
              <el-form-item class="deploy-create-form" label="副本数" prop="replicas">
                <el-input-number v-model="createDaemonset.replicas" :min="1" :max="10"></el-input-number>
                <!-- 气泡弹出框用于提醒上限 -->
                <el-popover
                    placement="top"
                    :width="100"
                    trigger="hover"
                    content="申请副本数上限为10个">
                  <template #reference>
                    <el-icon style="width:2em;font-size:18px;color:#4795EE"><WarningFilled/></el-icon>
                  </template>
                </el-popover>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="镜像" prop="image">
                <el-input v-model="createDaemonset.image"></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="标签" prop="label_str">
                <el-input v-model="createDaemonset.label_str" placeholder="示例: project=ms,app=gateway"></el-input>
              </el-form-item>
              <!-- 下拉框，用于规格的选择，之后用/分割，得到cpu和内存 -->
              <el-form-item class="deploy-create-form" label="资源配额" prop="resource">
                <el-select v-model="createDaemonset.resource" placeholder="请选择">
                  <el-option value="0.5/1" label="0.5C1G"></el-option>
                  <el-option value="1/2" label="1C2G"></el-option>
                  <el-option value="2/4" label="2C4G"></el-option>
                  <el-option value="4/8" label="4C8G"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="容器端口" prop="container_port">
                <el-input v-model="createDaemonset.container_port" placeholder="示例: 80"></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="健康检查" prop="health">
                <el-switch v-model="createDaemonset.health_check" />
              </el-form-item>
              <el-form-item class="deploy-create-form" label="检查路径" prop="healthPath">
                <el-input v-model="createDaemonset.health_path" placeholder="示例: /health"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </template>
      <!-- 插槽，抽屉footer -->
      <template #footer>
        <!-- 点击后赋值false，隐藏抽屉 -->
        <el-button @click="createDaemonsetDrawer=false">取消</el-button>
        <el-button type="primary" @click="submitForm('createDaemonset')">立即创建</el-button>
      </template>
    </el-drawer>
    <!--YAML信息-->
    <el-dialog title="YAML信息" v-model="yamlDialog" width="45%" top="5%">
      <codemirror
          :value="contentYaml"
          border
          :options="cmOptions"
          height="500"
          style="font-size:14px;"
          @change="onChange"
      ></codemirror>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="yamlDialog = false">取 消</el-button>
                    <el-button type="primary" @click="updateDaemonSet()">更 新</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import common from '../../common/Config'
import httpClient from '@/request'
import yaml2obj from 'js-yaml';
import json2yaml from 'json2yaml';
export default {
  data() {
    return {
      //编辑器配置
      cmOptions: common.cmOptions,
      contentYaml: '',
      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10, 20, 30],
      //
      createDaemonsetDrawer: false,
      searchValue: '',
      namespaceValue: 'default',
      namespaceList: [],
      namespaceListUrl: common.k8sNamespaceList,
      appLoading: false,
      daemonSetList: [],
      daemonSetTotal: 0,
      getDaemonSetsData: {
        url: common.k8sDaemonSetList,
        params: {
          pool:'',
          filter_name: '',
          namespace: '',
          page: '',
          limit: '',
        }
      },
      //创建
      createDaemonset: {
        pool:"",
        name: '',
        namespace: '',
        replicas: 1,
        image: '',
        resource: '',
        health_check: false,
        health_path: '',
        label_str: '',
        label: {},
        container_port: ''
      },
      createDaemonsetData: {
        url: common.k8sDaemonSetCreate,
        params: {
          pool:"",
        }
      },
      //创建deployment的表单校验规则
      createDaemonsetRules: {
        name: [{
          required: true,
          message: '请填写名称',
          trigger: 'change'
        }],
        image: [{
          required: true,
          message: '请填写镜像',
          trigger: 'change'
        }],
        namespace: [{
          required: true,
          message: '请选择命名空间',
          trigger: 'change'
        }],
        resource: [{
          required: true,
          message: '请选择配额',
          trigger: 'change'
        }],
        label_str: [{
          required: true,
          message: '请填写标签',
          trigger: 'change'
        }],
        container_port: [{
          required: true,
          message: '请填写容器端口',
          trigger: 'change'
        }],
      },

      //详情
      daemonSetDetail: {},
      getDaemonSetDetailData: {
        url: common.k8sDaemonSetDetail,
        params: {
          pool:"",
          daemonset_name: '',
          namespace: ''
        }
      },
      //yaml更新
      yamlDialog: false,
      updateDaemonSetData: {
        url: common.k8sDaemonSetUpdate,
        params: {
          pool:"",
          namespace: '',
          content: ''
        }
      },
      //删除
      delDaemonSetData: {
        url: common.k8sDaemonSetDel,
        params: {
          pool:"",
          daemonset_name: '',
          namespace: '',
        }
      }
    }
  },
  methods: {
    transYaml(content) {
      return json2yaml.stringify(content)
    },
    transObj(content) {
      return yaml2obj.load(content)
    },
    onChange(val) {
      this.contentYaml = val
    },
    handleSizeChange(size) {
      this.pagesize = size;
      this.getDaemonSets()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getDaemonSets()
    },

    npChange() {
      this.getDaemonSets()
      localStorage.setItem('namespace', this.namespaceValue)
    },

    //创建
    createDaemonsetFunc() {
      //验证标签合法性
      let reg = new RegExp("(^[A-Za-z]+=[A-Za-z0-9]+).*")
      if (!reg.test(this.createDaemonset.label_str)) {
        this.$message.warning({
          message: "标签验证不通过，请重新填写"
        })
        return
      }
      //处理标签和规格
      this.appLoading = true
      let label = new Map()
      let cpu, memory
      let a = (this.createDaemonset.label_str).split(",")
      a.forEach(item => {
        let b = item.split("=")
        label[b[0]] = b[1]
      })
      let resourceList = this.createDaemonset.resource.split("/")
      cpu = resourceList[0]
      memory = resourceList[1] + "Gi"
      //赋值
      this.createDaemonsetData.params = this.createDaemonset
      this.createDaemonsetData.params.container_port = parseInt(this.createDaemonset.container_port)
      this.createDaemonsetData.params.label = label
      this.createDaemonsetData.params.cpu = cpu
      this.createDaemonsetData.params.memory = memory
      this.createDaemonsetData.params.pool = localStorage.getItem('pool')
      //this.createDaemonsetData.params.pool = this.k8sValue

      httpClient.post(this.createDaemonsetData.url, this.createDaemonsetData.params)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
            this.resetForm('createDaemonset')
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            this.getDaemonSets()
            this.createDaemonsetDrawer = false
            this.appLoading = false
          })
    },
    //提交表单，验证数据
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        console.log(this.$refs.formName);
        if (valid) {
          this.createDaemonsetFunc()
        } else {
          return false
        }
      })
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    handleClose() {
      this.createDaemonsetDrawer = false
    },

    ellipsis(value) {
      return value.length>15?value.substring(0,15)+'...':value
    },
    timeTrans(timestamp) {
      let date = new Date(new Date(timestamp).getTime() + 8 * 3600 * 1000)
      date = date.toJSON();
      date = date.substring(0, 19).replace('T', ' ')
      return date
    },
    restartTotal(e) {
      let index, sum = 0
      let containerStatuses = e.row.status.containerStatuses
      for ( index in containerStatuses) {
        sum = sum + containerStatuses[index].restartCount
      }
      return sum
    },
    getNamespaces() {
      httpClient.get(this.namespaceListUrl)
          .then(res => {
            this.namespaceList = res.data.items
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },
    getDaemonSets() {
      this.appLoading = true
      this.getDaemonSetsData.params.filter_name = this.searchValue
      this.getDaemonSetsData.params.namespace = this.namespaceValue
      this.getDaemonSetsData.params.page = this.currentPage
      this.getDaemonSetsData.params.limit = this.pagesize
      this.getDaemonSetsData.params.pool = localStorage.getItem('pool')
      console.log(this.getDaemonSetsData.params.pool)

      httpClient.get(this.getDaemonSetsData.url, {params: this.getDaemonSetsData.params})
          .then(res => {
            this.daemonSetList = res.data.items
            this.daemonSetTotal = res.data.total
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
      this.appLoading = false
    },
    getDaemonSetDetail(e) {
      this.getDaemonSetDetailData.params.daemonset_name = e.row.metadata.name
      this.getDaemonSetDetailData.params.namespace = this.namespaceValue
      this.getDaemonSetDetailData.params.pool = localStorage.getItem('pool')
      httpClient.get(this.getDaemonSetDetailData.url, {params: this.getDaemonSetDetailData.params})
          .then(res => {
            this.daemonSetDetail = res.data
            this.contentYaml = this.transYaml(this.daemonSetDetail)
            this.yamlDialog = true
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },
    updateDaemonSet() {
      let content = JSON.stringify(this.transObj(this.contentYaml))
      this.updateDaemonSetData.params.namespace = this.namespaceValue
      this.updateDaemonSetData.params.content = content
      this.updateDaemonSetData.params.pool = localStorage.getItem('pool')
      httpClient.put(this.updateDaemonSetData.url, this.updateDaemonSetData.params)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
      this.yamlDialog = false
    },
    delDaemonSet(e) {
      this.delDaemonSetData.params.daemonset_name = e.row.metadata.name
      this.delDaemonSetData.params.namespace = this.namespaceValue
      this.delDaemonSetData.params.pool = localStorage.getItem('pool')
      httpClient.delete(this.delDaemonSetData.url, {data: this.delDaemonSetData.params})
          .then(res => {
            this.getDaemonSets()
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },
    handleConfirm(obj, operateName, fn) {
      this.confirmContent = '确认继续 ' + operateName + ' 操作吗？'
      this.$confirm(this.confirmContent,'提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
          .then(() => {
            fn(obj)
          })
          .catch(() => {
            this.$message.info({
              message: '已取消操作'
            })
          })
    },
  },
  watch: {
    namespaceValue: {
      handler() {
        localStorage.setItem('namespace', this.namespaceValue)
        this.currentPage = 1
        this.getDaemonSets()
      }
    },
  },
  beforeMount() {
    if (localStorage.getItem('namespace') !== undefined && localStorage.getItem('namespace') !== null) {
      this.namespaceValue = localStorage.getItem('namespace')
    }
    this.getNamespaces()
    this.getDaemonSets()
  },
}
</script>


<style scoped>
.daemonset-head-card,.daemonset-body-card {
  border-radius: 1px;
  margin-bottom: 5px;
}
.daemonset-head-search {
  width:160px;
  margin-right:10px;
}
.daemonset-body-daemonsetname {
  color: #4795EE;
}
.daemonset-body-daemonsetname:hover {
  color: rgb(84, 138, 238);
  cursor: pointer;
  font-weight: bold;
}
</style>